package club.mzywucai.blog.file_system.service.impl;

import club.mzywucai.blog.file_system.mapper.LoginAndRegisterMapper;
import club.mzywucai.blog.file_system.pojo.domain.JsonData;
import club.mzywucai.blog.file_system.pojo.domain.Judge;
import club.mzywucai.blog.file_system.pojo.domain.SendMail;
import club.mzywucai.blog.file_system.pojo.po.UserPo;
import club.mzywucai.blog.file_system.pojo.vo.UserVo;
import club.mzywucai.blog.file_system.service.LoginAndRegisterService;
import club.mzywucai.blog.file_system.util.CheckEmailUtil;
import club.mzywucai.blog.file_system.util.MD5Util;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author mzywucai
 * @Description
 * @date 2019/2/9
 */
@Service
@Data
@PropertySource(value={"classpath:config/application.properties"}, encoding = "UTF-8")
public class LoginAndRegisterServiceImpl implements LoginAndRegisterService {


    @Autowired
    LoginAndRegisterMapper loginAndRegisterMapper;

    @Override
    public JsonData getPhotoURI(HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");

        // un touch exception
        if (null == user) {
            return JsonData.buildError("系统异常");
        }

        UserPo userPo = loginAndRegisterMapper.searchUserByEmail(user.getEmail());

        // 重置一下session中的photoURI
        user.setPhotoURI(userPo.getPhotoURI());
        session.setAttribute("user", user);

        UserVo u = new UserVo();
        u.setPhotoURI(userPo.getPhotoURI());
        u.setEmail(userPo.getEmail());

        return JsonData.buildSuccess(0, u, "操作成功");
    }

    @Override
    public JsonData login(String email, String password, HttpSession session) {
        boolean check = CheckEmailUtil.check(email);
        if (!check) {
            return JsonData.buildError("邮箱格式不正确");
        }

        UserPo userPo = loginAndRegisterMapper.searchUserByEmail(email);

        if (null == userPo) {
            return JsonData.buildError("账户不存在，请前往注册。");
        }

        if (Judge.NO == userPo.getIsActivation()) {

            // error ok warning
            return JsonData.buildSuccess(1, "warning", "账户未激活，请前往邮箱激活。");
        }

        if (!MD5Util.checkPass(password, userPo.getPassword())) {
            return JsonData.buildError("密码错误");
        }

        UserVo user = new UserVo();

        user.setUserId(userPo.getUserId());
        user.setUserName(userPo.getUsername());
        user.setEmail(userPo.getEmail());
        user.setPhotoURI(userPo.getPhotoURI());
        user.setIsSilent(userPo.getIsSilent());

        session.setAttribute("user", user);

        return JsonData.buildSuccess(0, "ok", "登录成功");
    }


    @Value("${server.active.uri}")
    String activeURI;
    /**
     * @Description MZY记坑：这里是springboot 2.1.2版本，我新建的properties文件默认的编码是utf8的，但是
     * springboot读取的时候，无论是否按照网上的提醒加上@PropertySource(value={"classpath:config/resource.properties", "classpath:config/application.properties"}, encoding = "UTF-8")
     * resource.properties文件夹读出来的都是乱码！MD- 所以这里弃用resource.properties文件，配置全部移动到application.properties中。
     * @author mzywucai
     * @time 2019-02-10
     * @see
     * @return
     * @params
     */
    @Value("${server.mail.host}")
    private String mailHost;
    @Value("${server.mail.account}")
    private String username;
    @Value("${server.mail.password}")
    private String mailPassword;
    @Value("${server.mail.head.name}")
    private String mail_head_name;
    @Value("${server.mail.head.value}")
    private String mail_head_value;

    @Value("${server.mail.account}")
    private String mail_from;
    @Value("${server.mail.subject}")
    private String mail_subject;
    @Value("${server.mail.content}")
    private String mail_body;
    @Value("${server.mail.sender}")
    private String personalName;
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public JsonData register(String email, String password, HttpServletRequest request) {
        boolean check = CheckEmailUtil.check(email);
        UserPo userPo = loginAndRegisterMapper.searchUserByEmail(email);

        if (userPo != null && userPo.getIsActivation() == Judge.YES) {
            return JsonData.buildError("账户已存在");
        }

        if (userPo != null && userPo.getIsActivation() == Judge.NO) {
            return JsonData.buildError("账户已待激活");
        }

        if (!check) {
            return JsonData.buildError("邮箱格式不正确");
        }

        password = MD5Util.changePass(password);

        String UUIDString = UUID.randomUUID().toString();


        // 拿到HOST
        String uri = request.getRequestURI();
        String url = request.getRequestURL().toString();
        String host = url.replace(uri, "/");


        String activeURL = host + activeURI + UUIDString;

        SendMail sendMail = new SendMail();
        sendMail.setHost(mailHost);
        sendMail.setUsername(username);
        sendMail.setPassword(mailPassword);
        sendMail.setMail_head_name(mail_head_name);
        sendMail.setMail_head_value(mail_head_value);

        sendMail.setMail_from(mail_from);
        sendMail.setMail_subject(mail_subject);
        sendMail.setMail_body(mail_body);
        sendMail.setPersonalName(personalName);

        try {
            // System.out.println(sendMail);
            sendMail.send(email, activeURL);
        } catch (Exception e) {
            return JsonData.buildError("向指定邮箱发送激活链接失败");
        }

        loginAndRegisterMapper.addUser(email, password, UUIDString);

        return JsonData.buildSuccess(0, "ok", "请前往邮箱获取激活链接");
    }

    @Override
    public String activationBefore(String UUID) {
        UserPo userPo = loginAndRegisterMapper.searchUserByUuid(UUID);
        if (null != userPo) {
            return userPo.getEmail();
        }
        return null;
    }

    @Override
    public JsonData activation(String UUID, String username) {
        UserPo userPo = loginAndRegisterMapper.searchUserByUuid(UUID);
        if (null == userPo) {
            return JsonData.buildError("您激活的用户不存在");
        }
        if (userPo.getIsActivation() == Judge.YES) {
            return JsonData.buildSuccess(1, "ok", "用户已激活，请勿重复操作。");
        }


        loginAndRegisterMapper.updateUserActiveStatus(UUID, Judge.YES, username);

        return JsonData.buildSuccess(0, "ok", "激活成功");
    }

    @Override
    public JsonData updateUserPersonalSilentStatus(HttpSession session, int silentStatus) {
        UserVo user = (UserVo) session.getAttribute("user");

        // un touch exception
        if (null == user) {
            return JsonData.buildError("请先登录再进行操作");
        }

        Long userId = user.getUserId();

        if (silentStatus == 0) {
            loginAndRegisterMapper.updateUserPersonalSilentStatus(Judge.NO, userId);
            user.setIsSilent(Judge.NO);
        } else {
            loginAndRegisterMapper.updateUserPersonalSilentStatus(Judge.YES, userId);
            user.setIsSilent(Judge.YES);
        }

        session.setAttribute("user", user);

        return JsonData.buildSuccess(0, "ok", "ok");
    }
}
